/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package control;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 *
 * @author woutermkievit
 */
public class MailSender extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession sessie = request.getSession();
        SessionFactory sessionFactory = SchoolContentManager.sessionFactory;
        
        Session session = sessionFactory.getCurrentSession();
        Transaction transaction = session.beginTransaction();
        String to="";
        String emailSQL="";
        String toType=request.getParameter("to");
        if(toType.equals("all")){
            emailSQL = "SELECT g.email FROM gebruiker g";
            
        }else if(toType.equals("studens")){
            emailSQL = "SELECT s.email FROM student s";
        }else if(toType.equals("teachers")){
            emailSQL = "SELECT t.email FROM teacher t";
        }else if(toType.equals("admins")){
            emailSQL = "SELECT t.email FROM teacher t WHERE t.is_admin=true";
        }else{
            String ids=request.getParameter("to").replaceAll(",", "','");
            emailSQL = "SELECT s.email FROM student s WHERE s.ucode IN ('"+ids+"')";
            out.println(ids);
        }
        System.out.println("sql:   "+emailSQL);
            ArrayList<String> categories = (ArrayList<String>) session.createSQLQuery(emailSQL).list();
            out.println("sqlsize=       "+categories.size()+"<br>");
            for (int i = 0; i < categories.size(); i++) {
                
                    out.println(categories.get(i)+"<br>");
                if(checkmail(categories.get(i))){
                    to+=categories.get(i)+",";
                }
            
        }
            String mail="";
        if(to!=""){
            mail = new MailController().mail(request.getParameter("text"), request.getParameter("subject"), to);
            transaction.commit();
            sessie.setAttribute("contentPage", sessie.getAttribute("contentPage")+"announcement is sent to "+toType+".<br>"+mail+"<br>");
            response.sendRedirect("index");
        }else{
            sessie.setAttribute("contentPage", sessie.getAttribute("contentPage")+"No valid email.<br>"+mail+"<br>");
            
        }
        
    }
    public boolean checkmail(String email){
        //Set the email pattern string
      Pattern p = Pattern.compile(".+@.+\\.[a-z]+");

      //Match the given string with the pattern
      if(email==null){
        return false;  
      }else{
        Matcher m = p.matcher(email);
      

      //check whether match is found 
      boolean matchFound = m.matches();

      if (matchFound){
        //System.out.println("Valid Email Id.");
      
          return true;
      }else{
        //System.out.println("Invalid Email Id.");
        
          return false;
      }
   }
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
